#include "headfiles.h"

static int calcTwosOfaNum(int n) {
    int remaining;
    int res = n;
    int num_of_twos = 0;
    while (res > 0) {
        remaining = res % 10;
        if (remaining == 2) {
           ++num_of_twos;
        }
        res = res / 10;
    }

    return num_of_twos;
}

int calcTotalTwos(int n) {
    int i;
    int total_twos = 0;

    for (i = 2; i <= n; i++) {
        total_twos += calcTwosOfaNum(i);
    }

    return total_twos;
}

int calcTotalTwos1(int n) {
    int i;
    int total_twos = 0;
    int twos_tmp = 0;

    int remainings = 0;
    int digit_loc = 1;
    int res, rem;
    res = n;
    while (res > 0) {
        rem = res % 10;
        total_twos += rem * twos_tmp;
        if (rem == 2) {
            total_twos += remainings + 1;
        }
        else if (rem > 2) {
            total_twos += digit_loc;
        }

        remainings += rem * digit_loc;

        twos_tmp = 10 * twos_tmp + digit_loc;
        digit_loc *= 10;

        res = res / 10;
    }
    
    return total_twos;
}

